import React from 'react';
import { Form, Input, Button, message, Icon } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';

const formItemLayout = {
	wrapperCol: {
		xs: { span: 24 },
		sm: { span: 24 },
	},
};
const tailFormItemLayout = {
	wrapperCol: {
		xs: {
			span: 24,
		},
		sm: {
			span: 24,
		},
	},
};
const FormItem = Form.Item;

class Login extends React.PureComponent {
	constructor(props) {
		super(props);
		this.state = {};
	}

	submit = e => {
		e.preventDefault();
		const that = this;
		const { form, dispatch } = that.props;
		form.validateFieldsAndScroll((err, values) => {
			if (!err) {
				dispatch({
					type: 'user/login',
					payload: { ...values },
					callback: data => {
						localStorage.setItem('userInfo', JSON.stringify(data));
						message.success('登录成功!');
						router.push('/graphic');
					},
				});
			}
		});
	};
	username = (rule, values, callback) => {
		if (values !== 'admin') {
			callback('用户名为admin');
		} else {
			callback();
		}
	};
	password = (rule, values, callback) => {
		if (values !== 'admin') {
			callback('密码为admin');
		} else {
			callback();
		}
	};
	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<div style={{ width: 360, margin: '0 auto' }}>
				<Form onSubmit={this.submit}>
					<FormItem {...formItemLayout}>
						{getFieldDecorator('username', {
							rules: [
								{ required: true, message: '用户名不能为空' },
								// { validator: this.username },
							],
							validateTrigger: 'onBlur',
						})(
							<Input
								placeholder="用户名"
								size="large"
								prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
							/>
						)}
					</FormItem>
					<FormItem {...formItemLayout}>
						{getFieldDecorator('password', {
							rules: [
								{ required: true, message: '密码不能为空' },
								// { validator: this.password },
							],
							validateTrigger: 'onBlur',
						})(
							<Input
								type="password"
								placeholder="密码"
								size="large"
								prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
							/>
						)}
					</FormItem>
					<FormItem {...tailFormItemLayout}>
						<Button htmlType="submit" type="primary" size="large" block>
							登录
						</Button>
						{/* <Button
							type="normal"
							onClick={() => router.push('/user/signup')}
							size="large"
							block
							style={{ margin: '10px 0' }}
						>
							注册
						</Button> */}
					</FormItem>
				</Form>
			</div>
		);
	}
}

export default Form.create()(connect()(Login));
